import now from "../util/now"

function throttle(func: Function, wait: number, options: { [key: string]: any } = {}) {
  var timeout: number
  var context: any
  var args: any[]
  var result: any
  var previous = 0
  var later = function () {
    previous = options.leading === false ? 0 : now()
    timeout = null
    result = func.apply(context, args)
    if (!timeout) context = args = null
  }
  function throttled(...args1: any[]) {
    var now1 = now()
    if (!previous && options.leading === false) previous = now1
    var remaining = wait - (now1 - previous)
    context = this
    args = args1
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      previous = now1
      result = func.apply(context, args)
      if (!timeout) context = args = null
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining)
    }
    return result
  }
  throttled.cancel = function () {
    clearTimeout(timeout)
    previous = 0
    timeout = context = args = null
  }

  return throttled
}

export default throttle